<?php

namespace app\api\controller;

use app\common\model\Store as StoreModel;
use think\Db;
use app\api\validate\Store as StoreValidate;
use app\common\model\QueueRule;
use app\api\validate\QueueRule as QueueRuleValidate;
use app\common\model\Order;
use app\common\model\CommissionLog;
use app\common\model\ViperUser;
use app\common\model\ViperCardRechargeLog;
use app\common\model\ViperCard;

/**
 * 库存管理--商品分类控制器
 * @package app\index\controller
 */
class Store extends Auth
{
    public $noNeedLogin = '';


    /**
     * 设置门店--获取门店详情
     */
    public function detail()
    {
        if ($this->request->isPost()) {
            $info = StoreModel::where('id', $this->store_id)->find();
            $queue_rule = QueueRule::get(['store_id' => $this->store_id]);
            $info['queue_type'] = !empty($queue_rule['type']) ? $queue_rule['type'] : 0;
            $this->result('获取成功', $info, 200);
        } else {
            $this->result('请求错误', '', 204);
        }
    }

    /**
     * 设置门店--修改门店信息
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new StoreValidate();
            if (!$validate->check($data)) {
                $this->result($validate->getError(), '', 204);
            }
            unset($data['id']);
            StoreModel::where('id', $this->store_id)->update($data);
            $this->result('操作成功', '', 200);
        } else {
            $this->result('请求错误', '', 204);
        }

    }

    /**
     * 设置门店--获取门店排钟规则
     */
    public function getQueue()
    {
        if ($this->request->isPost())
        {
            $getData = $this->request->post();
            if(empty($getData['type'])){
                $this->result('缺少参数','',204);
            }
            $info = QueueRule::where('type',$getData['type'])->get(['store_id'=>$this->userInfo['store_id']]);

            $info = isset($info)?$info:[];

            $this->result('获取成功',$info,200);
        }else{
            $this->result('请求错误','',204);
        }
    }

    /**
     * 设置门店--修改排钟规则
     * queue_id  type  is_working_engineer_first
     * is_working_dot_act is_overtime_dot_act
     * is_overtime_auto_queue rule  is_overtime_act_queue
     * second_act_type is_down_act
     */
    public function queue()
    {
        $data = $this->request->post();

        $validate = new QueueRuleValidate();

        if (!$validate->check($data))
        {
            $this->result($validate->getError(),'',204);
        }

        if (!empty($data['id']))
        {
            $msg = QueueRule::where('id',$data['id'])->update($data);
        }else{
            $find = Db::name('qt_queue_rule')
                ->where('store_id',$this->userInfo['store_id'])->where('type',$data['type'])
                ->find();
            if(!empty($find)){
                $this->result('当前门店有排钟规则，不支持新增','',204);
            }
            $data['store_id'] = $this->userInfo['store_id'];
            $msg = QueueRule::create($data);
        }

        $msg?$this->result('更新成功','',200):$this->result('提交信息与原信息相同','',204);

    }

    /**
     * 门店业绩
     * type
     */
    public function commission()
    {
        $data = $this->request->post();

        switch ($data['type']) {
            case 1:
                $map = 'today';
                break;
            case 2:
                $map = 'yesterday';
                break;
            case 3:
                $map = 'month';
                break;
            case 4:
                $map = 'last month';
                break;
        }
        //营业总额
        $business_total = CommissionLog::whereTime('created_time', $map)
            ->where('store_id', $this->userInfo['id'])
            ->sum('money');
        //现金业绩
        $cash_commission = CommissionLog::where('store_id', $this->userInfo['id'])
            ->where('pay_type', 1)
            ->sum('commission');
        //其他收入
        $other_income = CommissionLog::where('store_id', $this->userInfo['id'])
            ->where('pay_type', 'neq', 1)
            ->sum('money');
        //现金消费
        $cash_expense = Order::whereTime('created_time', $map)
            ->where('store_id', $this->userInfo['id'])
            ->where('pay_type', 1)
            ->sum('money');
        //售卡业绩
        $sale_card_commission = CommissionLog::whereTime('created_time', $map)
            ->where('store_id', $this->userInfo['id'])
            ->where('type', 3)
            ->sum('commission');
        //新增会员数
        $new_user_count = ViperUser::where('create_time', $map)
            ->where('store_id', $this->userInfo['id'])
            ->count('user_id');
        //商品业绩
        $product_commission = CommissionLog::where('created_time', $map)
            ->where('store_id', $this->userInfo['id'])
            ->where('type', 2)
            ->sum('commission');
        //消费人数
        $expense_number = CommissionLog::where('created_time', $map)
            ->where('store_id', $this->userInfo['id'])
            ->count('user_id');
        //人均消费
        $avg_expense = round($business_total / $expense_number, 2);
        //会员消费数
        $viper_expense = CommissionLog::alias('c')
            ->leftJoin('dp_qt_user_viper v', 'v.id=c.user_id')
            ->where('c.store_id', $this->userInfo['id'])
            ->where('v.is_viper', 1)
            ->sum('money');
        //续费会员数
        $recharge_user_number = ViperCardRechargeLog::whereTime('create_time', $map)
            ->where(['store_id' => $this->userInfo['id']])
            ->count('user_id');
        //会员赠送
        $user_give = ViperCard::whereTime('create_time', $map)
            ->where('store_id', $this->userInfo['id'])
            ->sum('give_total_amount');

        $this->result('获取成功', [
            'business_total' => $business_total,
            'cash_commission' => $cash_commission,
            'other_income' => $other_income,
            'cash_expense' => $cash_expense,
            'sale_card_commission' => $sale_card_commission,
            'new_user_count' => $new_user_count,
            'product_commission' => $product_commission,
            'expense_number' => $expense_number,
            'avg_expense' => $avg_expense,
            'viper_expense' => $viper_expense,
            'recharge_user_number' => $recharge_user_number,
            'user_give' => $user_give,
        ], 200);

    }

    /**
     * 获取当前门店活动
     */
    public function activity()
    {
        if ($this->request->isPost()) {
            $data = Db::name('qt_data_activity')
                ->field('id,name as title')
                ->where(['store_id' => $this->userInfo['store_id']])
//                ->whereTime('date_start', '<=', time())
//                ->whereTime('date_end', '>=', time())
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 切换门店
     */
    public function switch(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['store_id'])){
                $this->result('缺少参数', '', 204);
            }
            if($this->userInfo['store_id'] == $getData['store_id']){
                $this->result('切换门店和当前登录门店一致', '', 204);
            }
            Db::name('qt_users')->where(['id'=>$this->userInfo['id']])->update(['store_id'=>$getData['store_id']]);
            $this->result('切换成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 用户门店列表
     */
    public function lists(){
        if ($this->request->isPost()) {
            $data = Db::name('qt_user_store')
                ->field('s.id,s.name as store_name,s.avatar,s.address')
                ->alias('us')
                ->leftJoin('qt_store s','s.id = us.store_id')
                ->where(['us.user_id'=>$this->userInfo['id']])
                ->select();
            foreach ($data as $key=>$value){
                $data[$key]['avatar'] = get_img_path($value['avatar']);
            }
            $result['store_id'] = $this->userInfo['store_id'];
            $result['data'] = $data;
            $this->result('查询成功', $result, 200);
        }
        $this->result('无效的请求', '', 204);
    }


}
